/**
 * Created by ZFL on 2018/1/9.
 */

function appInit() {
    PageInit();
}
function PageInit() {
    if(com_obj.userId>0){
        //初始化
        app.cartView();
    }else{
        $.showLogin();
    }
}
var imgUrl=[];   //存放上传照片的url
var app = new Vue({
    el:'#app',
    data:{
        isRefund:0,
        pageShow:false,
        after:{}
    },
    filters:{
        fStatus:function (value) {
            var text ='';
            switch (value){
                case 2:
                case "2":
                    text = "待发货";
                    break;
                case 3:
                case "3":
                    text = "待收货";
                    break;
                case 4:
                case "4":
                    text = "已完成";
                    break;
            }
            return text;
        },
        formatMoney:function (value) {
            var _value=0;
            if(value){
                _value = divideNumber(value,100);
            }
            return _value;
        }
    },
    mounted:function () {
        this.$nextTick(function () {
        });
    },
    methods:{
        cartView:function () {
            //获取订单详情
            orderInfo();
        },
        checkAfter:function(){
            if(app.isRefund==0){
                YDUI.dialog.toast('请选择退款类型', 'none', 1000);
            }else if($("#selectId").val()==""){
                YDUI.dialog.toast('请选择退款原因', 'none', 1000);
            }else if($("#after-explain").val()==""){
                YDUI.dialog.toast('请输入退款说明', 'none', 1000);
            }else if($("#after-explain").val().length<=6){
                YDUI.dialog.toast('退款说明最少6个字', 'none', 1000);
            }else if($("#after-explain").val().length>200){

                YDUI.dialog.toast('退款说明最多', 'none', 1000);
            }else{
                getImgUrl();
                $.ajaxHandler({
                    model: function () {
                        var obj = {};
                        obj.orderDetailId = $.getPara("orderDetailId");
                        obj.userId = com_obj.userId;
                        obj.type ="1";  //售后
                        obj.isRefund = app.isRefund;//退款类型
                        obj.userRefundReason =$("#selectId").val();//退款原因
                        obj.userFirstReason = $("#after-explain").val();//退款说明
                        obj.imgProof1=imgUrl[0];
                        obj.imgProof2=imgUrl[1];
                        obj.imgProof3=imgUrl[2];
                        //alert(JSON.stringify(obj));
                        return obj;
                    },
                    visibleTime: 0,
                    dataType: "json",
                    approve: true,
                    api: "yg_baijiaplatform/afterSales/ygBaSaveAfterSales",
                    success: function (result) {
                        console.log(result);
                        if (result.code == 10000) {
                            YDUI.dialog.toast('提交成功', 'success', 1000);
                            setTimeout(function () {
                                window.location.href='../customerSer/customerSer.html';
                            },1000);
                        } else {
                            YDUI.dialog.toast(result.message,'error',1000);
                        }
                    }
                });

            }
        },
        seelecType:function ($event) {
            var toggle = event.currentTarget;
            app.isRefund = $(toggle).attr("data-value");
            $(toggle).addClass('active').siblings().removeClass('active');
        }
    }
});

//加载订单详情
function orderInfo() {
    $.ajaxHandler({
        model: function () {
            var obj = {};
            obj.orderDetailId = $.getPara("orderDetailId");
            obj.userId = com_obj.userId;
            console.log(obj)
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        approve: true,
        api: "yg_baijiaplatform/afterSales/ygBaApplyAfterSales",
        success: function (result) {
            //console.log(result);
            if (result.code == 10000) {
                app.$set(app,"after",result.data);
                app.pageShow = true;
            } else {
                YDUI.dialog.toast(result.message,'error',function(){});
            }
        }
    });
}


function getObjectURL(file) {
    var url = null ;
    if (window.createObjectURL!=undefined) {  // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) {       // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL!=undefined) { // web_kit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
}

function convertImgToBase64(url, callback, outputFormat){
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var img = new Image;
    quality = 0.6, //image quality
        img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var width = img.width;
        var height = img.height;
        // 按比例压缩4倍
        var rate = (width<height ? width/height:height/width)/4;
        canvas.width = width*rate;
        canvas.height = height*rate;
        ctx.drawImage(img,0,0,width,height,0,0,width*rate,height*rate);

        var dataURL = canvas.toDataURL(outputFormat || 'image/png',quality);
        callback.call(this, dataURL);
        canvas = null;
    };
    img.src = url;
}

$('.uploadImgs').on('change','.showImgWrap input',function(){
   var _this=this;
    var imageUrl=getObjectURL($(this)[0].files[0]);
    convertImgToBase64(imageUrl,function(base64Img){
        // base64转图片不需要base64的前缀data:image/jpg;base64

        suffix=base64Img.split(';')[0].split('/')[1];    //图片后缀
        imgBase=base64Img.split(',')[1];    //base64
        var index=$(_this).parents('.showImgWrap').index();
        uploadIdImgs(suffix,imgBase,index)

    })
})
var urlNumber=0;   //上传图片的数目
//点击删除  删除图片
$('.uploadImgs').on('click','.showImgWrap img',function(){
    var index=$(this).parents('.showImgWrap').index();
    //如果上传三张图片   删除一张后  只剩两张   要保证最后一张是待上传状态   在删除前判断是否已上传三张
    getImgUrl();
    $('.showImgWrap')[index].remove();
    if(urlNumber==3){
        var string=' <div class="showImgWrap"> <div class="showImg"></div><input type="file" accept="image/*"><img src="../images/order/del.png" alt="" class="del"></div>';
        $($('.uploadImgs .showImgWrap')[index-1]).after(string)
    }



})


function uploadIdImgs(suf,base,ind){
    $.ajaxHandler({
        model:function(){
            var obj={};
            obj.catalog=1;
            obj.suffix=suf;
            obj.imgBase=base;
            console.log(obj)
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        approve: true,
        api: 'yg_platformgoods/common/imageBasePath',
        success:function(res){
            if(res.code==10000){
                var data=res.data;
                $($('.uploadImgs .showImg')[ind]).css({
                   'background-image':'url('+data+')'
               });
               $($('.uploadImgs .showImgWrap')[ind]).find('.del').show()


                //当照片数小于等于两个时   能动态加入
                if($('.showImgWrap').length<=2){
                    var string=' <div class="showImgWrap"> <div class="showImg"></div><input type="file" accept="image/*"><img src="../images/order/del.png" alt="" class="del"></div>';
                    $($('.uploadImgs .showImgWrap')[ind]).after(string)
                }

            }else{
                YDUI.dialog.toast(res.message,1000)
            }
        }
    })
}
//

function getImgUrl(){

    imgUrl=[];

    for(var i=0;i<$('.uploadImgs .showImg').length;i++){
        var url=($($('.uploadImgs .showImg')[i]).css('backgroundImage')).split('(')[1].split(')')[0];
        if(url.indexOf('submit.png')>0){
            url=''
        }else{
            urlNumber++;
        }

        imgUrl.push(url);

    }
}



//返回上一页
function returnBack() {
    window.history.back();  //返回上一页
}





